import {
  lazy,
  Suspense
} from 'react'

import { Navigate, useRoutes } from 'react-router-dom'

// 公共组件
import Loading from '../components/Loading'

// 懒加载路由 (路由文件开始不会打包到项目文件中而是生成单独的路由文件，等需要的时候在加载该路由文件)
const Login = lazy(() => import('../pages/Login'))
const Main = lazy(() => import('../pages/Mian'))
const NotFind = lazy(() => import('../pages/404'))

const About = lazy(() => import('../pages/Mian/About'))
const Home = lazy(() => import('../pages/Mian/Home'))

const News = lazy(() => import('../pages/Mian/Home/News'))
const Messages = lazy(() => import('../pages/Mian/Home/Messages'))

const load = (Compontent) => {
  return (
    <Suspense fallback={<Loading />}>
      <Compontent />
    </Suspense>
  )
}

const routes = [
  {
    path: '/login',
    element: load(Login)
  },
  {
    path: '/main',
    element: load(Main),
    children: [
      {
        path: '/main/about',
        element: load(About)
      },
      {
        path: '/main/home',
        element: load(Home),
        children: [
          {
            path: '/main/home/news/:id',
            element: load(News)
          },
          {
            path: '/main/home/messages/:id',
            element: load(Messages)
          }
        ]
      },
      {
        path: '/main/',
        element: <Navigate to='/main/about' />
      }
    ]
  },
  {
    path: '/',
    element: <Navigate to='/main' />  // 路由重定向
  },
  {
    path: '*',  // * 代表所有的路由都不匹配时匹配我（跟书写顺序无关）
    element: load(NotFind)
  }
]

export default routes

// hooks 在组件中使用
export const GetRoutes = () => {
  return (
    useRoutes(routes)
  )
}

// hooks 在 hooks 中使用
export const useMakeRoutes = () => {
  return useRoutes(routes)
}